<template>
  <div id="addImagePage">
    <h1 class="title">
      {{ route.query?.id ? '修改图片' : '创建图片' }}
    </h1>
    <a-typography-paragraph v-if="spaceId" type="secondary">
      保存至空间：<a :href="`/space/detail/${spaceId}`" target="_blank">{{ spaceId }}</a>
    </a-typography-paragraph>
    <!-- 选择上传方式 -->
    <a-tabs v-model:activeKey="uploadType">
      <a-tab-pane key="file" tab="文件上传">
        <UploadImage :image="image" :spaceId="spaceId" :onSuccess="onSuccess" />
      </a-tab-pane>
      <a-tab-pane key="url" tab="URL 上传" force-render>
        <UploadImageByUrl :image="image" :spaceId="spaceId" :onSuccess="onSuccess" />
      </a-tab-pane>
    </a-tabs>
    <div v-if="image" class="edit-bar">
      <a-space size="middle">
        <a-button :icon="h(EditOutlined)" @click="doEditImage">裁剪图片</a-button>
        <a-button type="primary" ghost :icon="h(FullscreenOutlined)" @click="doImageSynthesis">
          AI 扩图
        </a-button>
      </a-space>
      <ImageCropper
        ref="imageCropperRef"
        :imageUrl="image?.url"
        :image="image"
        :spaceId="spaceId"
        :space="space"
        :onSuccess="onCropSuccess"
      />
      <ImageSynthesisModal
        ref="imageSynthesisRef"
        :image="image"
        :spaceId="spaceId"
        :onSuccess="imageSynthesisSuccess"
      />
    </div>
    <a-form v-if="image" layout="vertical" :model="imageForm" @finish="handleSubmit">
      <a-form-item label="图片名称" name="name">
        <a-input v-model:value="imageForm.name" placeholder="请输入图片名称" allow-clear />
      </a-form-item>
      <a-form-item label="简介" name="introduction">
        <a-textarea
          v-model:value="imageForm.introduction"
          :rows="{ min: 2, max: 4 }"
          placeholder="请输入简介"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="分类" name="category">
        <a-auto-complete
          v-model:value="imageForm.category"
          :options="categoryOptions"
          placeholder="请输入分类"
          allowClear
        />
      </a-form-item>
      <a-form-item label="标签" name="tags">
        <a-select
          v-model:value="imageForm.tags"
          :options="tagOptions"
          mode="tags"
          placeholder="请输入标签"
          allowClear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">创建</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import UploadImage from '@/components/UploadImage.vue'
import { computed, onMounted, reactive, ref, h, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import {
  editImageUsingPost,
  getImageVoByIdUsingPost,
  listImageTagCategoryUsingGet,
} from '@/api/imageController.ts'
import UploadImageByUrl from '@/components/UploadImageByUrl.vue'
import ImageCropper from '@/components/ImageCropper.vue'
import { EditOutlined, FullscreenOutlined } from '@ant-design/icons-vue'
import ImageSynthesisModal from '@/components/ImageSynthesisModal.vue'
import { getSpaceVoByIdUsingPost } from '@/api/spaceController.ts'

// 空间 id
const spaceId = computed(() => {
  return route.query?.spaceId
})

// 上传图片形式（文件/URL）
const uploadType = ref<'file' | 'url'>('file')

/**
 * 图片上传成功回调
 */
const image = ref<API.ImageVO>()
const imageForm = reactive<API.ImageEditRequest>({})
const onSuccess = (newImage: API.ImageVO) => {
  image.value = newImage
  imageForm.name = newImage.name
}

/**
 * 提交表单
 */
const router = useRouter()
const handleSubmit = async (values: any) => {
  const imageId = image.value.id

  const res = await editImageUsingPost({
    id: imageId,
    spaceId: spaceId.value,
    ...values,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('图片创建成功')
    // 跳转到图片详情页
    router.push({
      path: `/image/detail/${imageId}`,
    })
  } else {
    message.error('创建失败，' + res.data.message)
  }
}

/**
 * 获取标签和分类选项
 */
const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])
const getTagCategoryOptions = async () => {
  const res = await listImageTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // 转换成下拉选项组件接受的格式
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('加载选项失败，' + res.data.message)
  }
}

// 编辑图片的时候回显数据
const route = useRoute()
const getOldImage = async () => {
  // 获取数据
  const id = route.query?.id
  if (id) {
    const res = await getImageVoByIdUsingPost({
      id: id as number,
    })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      image.value = data
      imageForm.name = data.name
      imageForm.introduction = data.introduction
      imageForm.category = data.category
      imageForm.tags = data.tags
    }
  }
}

// 页面加载就会执行一次
onMounted(() => {
  getTagCategoryOptions()
  getOldImage()
})

// -----  图片编辑弹窗引用  -----
const imageCropperRef = ref()
// 编辑图片
const doEditImage = () => {
  if (imageCropperRef.value && image.value?.url) {
    imageCropperRef.value.openModal()
  }
}
// 编辑成功事件
const onCropSuccess = (newImage: API.ImageVO) => {
  image.value = newImage
}

// ----- AI 扩图弹窗引用  -----
const imageSynthesisRef = ref()

// AI 扩图
const doImageSynthesis = () => {
  // 图像分辨率：图像的宽度和高度范围为[512, 4096]像素
  if(image.value?.imgHeight > 4096 || image.value?.imgWidth > 4096
  || image.value?.imgHeight < 512 || image.value?.imgWidth < 512) {
    message.warn('请选择图像的宽度和高度范围为[512, 4096]之间的图片')
    return
  }
  // 图像大小：不超过10MB
  if(image.value?.imgSize > 10 * 1024 * 1024) {
    message.warn('请选择大小不超过10MB的图片')
    return
  }
  if (imageSynthesisRef.value) {
    imageSynthesisRef.value.openModal()
  }
}

// 编辑成功事件
const imageSynthesisSuccess = (newPicture: API.ImageVO) => {
  image.value = newPicture
}

const space = ref<API.SpaceVO>()

// 获取空间信息
const fetchSpace = async () => {
  // 获取数据
  if (spaceId.value) {
    const res = await getSpaceVoByIdUsingPost({
      id: spaceId.value,
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    }
  }
}

watchEffect(() => {
  fetchSpace()
})
</script>

<style scoped>
#addImagePage {
  max-width: 720px;
  margin: 0 auto;
}

#addImagePage .title {
  text-align: center;
  margin-bottom: 16px;
  font-size: 36px;
  font-weight: bold;
}

#addImagePage .edit-bar {
  text-align: center;
  margin: 16px 0;
}
</style>
